<template>
    <div>
        <el-container>
            <!-- 未勾选文件列表时展示 -->
            <el-header v-if="!checkFile">
                <!-- 操作列表 -->
               
                <el-button type="primary" @click="uploadCheck()">上传文件<i
                        class="el-icon-upload el-icon--right"></i></el-button>
                <el-button @click="openNewFolder" type="primary">新建文件夹 <i class="el-icon-circle-plus"></i></el-button>
                <span v-if="checkNewFolder">
                    <el-input v-model="newFolderName" placeholder="新建文件夹名称"
                        style="width: auto;margin-left: 10px;"></el-input>
                    <el-button @click="okNewFolder" type="success" icon="el-icon-check"></el-button>
                </span>



                <!-- 上传组件 -->
                <el-drawer title="上传文件" size="40%" :visible.sync="uploadVisible" direction="rtl" :append-to-body="true">
                    <div class="upload">
                        <el-upload class="upload-demo" action="none" ref="uploadRef" :on-preview="handlePreview"
                            :on-remove="handleRemove" :on-change="uploadChange" :headers="uploadHeaders" :data="uploadData"
                            :file-list="fileList" :auto-upload="false" multiple>
                            <el-button slot="trigger" size="small" type="primary" @click="delFile">选取文件</el-button>
                            <el-button style="margin-left: 10px;" size="small" type="success"
                                @click="uploadSubmit">上传到服务器</el-button>
                            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                            <el-progress v-show="percentShow" :percentage="progressPercent" />

                        </el-upload>
                    </div>
                </el-drawer>

                <!-- <el- title="开始上传文件" :visible.sync="uploadVisible"  width="50%" >
                    
                </el-dialog> -->
            </el-header>

            <!-- 勾选文件列表时展示 -->
            <el-header v-if="checkFile">
                <el-row>
                    <el-button :disabled=disabledDownFlag type="primary" @click="download">批量下载<i
                            class="el-icon-upload el-icon--right"></i></el-button>
                    <el-button type="primary" disabled>批量删除<i class="el-icon-upload el-icon--right"></i></el-button>
                    <el-button type="info" plain disabled>更多批量操作正在开发...</el-button>
                </el-row>

            </el-header>
            <el-main>
                <!-- 文件路径 -->
                <!-- 面包屑实现 -->

                <el-breadcrumb class="bread-crumb" separator="/">
                    <el-breadcrumb-item @click.native="changeBread('all')">全部文件</el-breadcrumb-item>
                    <el-breadcrumb-item v-for="item in folderData" :key="item.id" @click.native="changeBread(item)">{{
                        item.displayName
                    }}</el-breadcrumb-item>
                </el-breadcrumb>
                <hr>
                <div>
                    <!-- 文件列表 -->
                    <el-table v-if="tableData" ref="multipleTable" :data="tableData" tooltip-effect="dark"
                        style="width: 100%" @selection-change="handleSelectionChange" @row-contextmenu="rowContextmenu"
                        height=70vh>
                        <el-table-column type="selection" width="55">
                        </el-table-column>
                        <el-table-column label="格式" width="100">
                            <template slot-scope="scope">
                                <i v-if="scope.row.sort == 0" class="el-icon-folder myfoldericon"></i><!-- 文件夹 -->
                                <i v-else-if="scope.row.sort == 1" class='el-icon-document myicon'></i><!-- 文档 -->
                                <i v-else-if="scope.row.sort == 2" class='el-icon-picture-outline myicon'></i><!-- 图片 -->
                                <i v-else-if="scope.row.sort == 3" class='el-icon-service myicon'></i><!-- 音频 -->
                                <i v-else-if="scope.row.sort == 4" class='el-icon-video-camera-solid myicon'></i><!-- 视频 -->
                                <i v-else-if="scope.row.sort == 5" class='el-icon-collection myicon'></i><!-- 压缩包 -->
                            </template>
                        </el-table-column>
                        <el-table-column label="文件名" width="550">
                            <template slot-scope="scope">
                                <div @click="clickFileTable(scope.row)">{{ scope.row.displayName }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column label="分享" width="50">
                            <template slot-scope="scope">
                                <div v-if="scope.row.sort != 0">
                                    <span class="u-btn" @click="shareFile(scope.row)"><i class="el-icon-share"></i></span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="删除" width="50">
                            <template slot-scope="scope">
                                <div v-if="scope.row.sort != 0">
                                    <span class="u-btn" @click="deleteFile(scope.row)"><i class="el-icon-delete"></i></span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="displaySize" label="大小/MB" width="120" align="center">
                        </el-table-column>
                        <el-table-column prop="updateTime" label="更新时间" width="auto" show-overflow-tooltip>
                        </el-table-column>
                    </el-table>
                    <context-menu v-if="menuVisible" @foo="foo" ref="contextbutton" @handleOne="handleOne"
                        @handleTwo="handleTwo" @handleThree="handleThree" @handleZero="handleZero"></context-menu>
                </div>

                <!-- 重命名表单 -->
                <el-dialog title="重命名" :visible.sync="renameVisible" width="30%" :append-to-body="true">
                    <el-input v-model="renameInput">
                        <template slot="prepend">新名称: </template>
                    </el-input>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="renameVisible = false">取 消</el-button>
                        <el-button type="primary" @click="upRename">确 定</el-button>
                    </span>
                </el-dialog>
            </el-main>
            <div>

            </div>
        </el-container>

    </div>
</template>

<script>
import request from '../../utils/request'
import allfileAPI from '../../api/allfile'
import Cookie from "js-cookie";
import SparkMD5 from 'spark-md5'
import contextMenu from '../../components/contextMenu.vue'
import ShareFileAPI from '../../api/share'
import loginAPI from '../../api/login'


const options = {
    data() {
        return {
            selectName: '',//输入搜索内容
            newFolderName: '',//新建文件夹输入名称
            checkFile: false,//是否选中文件选框
            uploadVisible: false,//是否展开上传文件小页面
            checkNewFolder: false,//是否展开新建文件夹组件
            tableData: [{
                'sort': 0,
                'displayName': 'wowowo',
                'fileSize': 3,
                'updateTime': '今天'
            }],//文件列表数据
            //模拟文件夹面包屑数据
            folderData: [],
            clickfolderflag: true,//是否能点击文件夹标识
            //当前页面文件路径(默认/')
            path: '/',
            fileList: [],//上传文件集合
            uploadHeaders: {
                Authorization: Cookie.get('token')
            },
            uploadData: {
                dataType: "0",
                oldFilePath: ""
            },
            progressPercent: 0, // 进度条默认为0
            percentShow: false,//进度条显示
            multipleSelection: [],//当前被选中的
            disabledDownFlag: false,//禁用上传按钮
            moveDrawer: false,//移动页面
            menuVisible: false,//右键菜单窗口
            fileOne: null,//单个文件
            renameVisible: false,//重命名对话框
            renameInput: '',//重命名名称





        }
    },
    components: {
        contextMenu
    },
    methods: {
        //点击新建文件夹事件
        openNewFolder() {
            this.checkNewFolder = true;
        },
        //确定新建文件夹名称事件
        okNewFolder() {
            this.checkNewFolder = false;
            //如果设置的文件名为空 就直接取消新建逻辑
            if (!this.newFolderName) {
                this.$message.warning("该文件夹名不允许为空!")
                return
            }
            let data = {};
            data.displayName = this.newFolderName;
            data.path = this.path
            //看看有无重名的
            for (const item of this.tableData) {
                if (item.displayName === this.newFolderName) {
                    this.$message.error("该文件夹名已存在!");
                    return;
                }
            }
            //没有重名就提交名称到后端
            allfileAPI.newFolderNameApi(data).then(res => {
                this.$message.success(res.data.data);
                //创建完成之后又查询一下当前文件列表
                this.selectFileList();
            })
            this.newFolderName = ''

        },
        //勾选切换事件
        handleSelectionChange(val) {
            //勾选到文件夹时禁用下载按钮
            let flag = false;
            if (val.length === 4) {
                //超过三个先不让下载了
                this.$message.warning("暂时只支持最多下载三个文件!")
                flag = true
            }
            for (let item of val) {
                if (item.sort === 0) {
                    //是文件夹时禁用下载按钮
                    flag = true
                    continue
                }
            }
            this.disabledDownFlag = flag

            console.log(val)
            if (val.length === 0) {
                this.checkFile = false
            } else {
                this.checkFile = true
            }
            //被选中的东西赋值上去
            this.multipleSelection = val;
        },
        //加载文件列表
        selectFileList() {
            //传递参数文件路径
            let params = {
                'path': this.path
            }
            //发送请求获取文件列表数据
            allfileAPI.findFileListApi(params).then(res => {
                //把数据存入表格数组
                this.tableData = res.data.data
                this.clickfolderflag = true
            })
        },
        //点击文件夹/文件名切换事件
        clickFileTable(row) {
            console.log(row)
            //如果是文件夹并且标识为true 那么就加入面包屑数据
            if (row.sort === 0 && this.clickfolderflag) {
                this.clickfolderflag = false;
                console.log("已点击到文件夹")
                this.folderData.push(row)
                console.log(this.folderData)
                if (this.path === '/') {
                    this.path = this.path + row.displayName;
                } else {
                    this.path = this.path + '/' + row.displayName
                }
                //  console.log(this.params)
                //  //又开始获取表格数据
                this.selectFileList()
            }
        },
        //改变面包屑导航
        changeBread(row) {
            if (row === 'all') {
                this.path = '/'
                this.folderData = []
            } else {
                let myindex = 0;
                //遍历整个数组
                for (let i = 0; i < this.folderData.length; i++) {
                    if (this.folderData[i].displayName === row.displayName) {
                        myindex = i
                        console.log(myindex)
                    }
                }
                this.folderData.splice(myindex + 1, this.folderData.length - myindex - 1);
                console.log(this.folderData)
                //既要删除面包数组里的 也要改变path
                let changePath = '/'
                for (let item of this.folderData) {
                    if (changePath === '/') {
                        changePath = changePath + item.displayName
                    } else {
                        changePath = changePath + '/' + item.displayName
                    }
                }
                this.path = changePath;
            }
            this.selectFileList()
        },
        //上传请求自定义
        async uploadSubmit() {
            if (this.fileList.length === 0) {
                this.$message.warning("请选择文件上传!")
                return
            }
            let formdata = new FormData();
            formdata.append("path", this.path)
            for (let file of this.fileList) {
                formdata.append("files", file.raw);
                //获取文件md5
                let fileMd5 = await this.getFileMD5(file);
                console.log("文件md5：", fileMd5)
                formdata.append("md5s", fileMd5);
            }
            await request({
                method: 'post',
                url: '/file/upload',
                data: formdata,
                onUploadProgress: progressEvent => {
                    const complete = parseInt(
                        ((progressEvent.loaded / progressEvent.total) * 100) | 0, 10)
                    this.progressPercent = complete //上传进度
                }
            }).then(info => {
                console.log(info)
                if (info.data.data) {
                    this.$message.success(info.data.data)

                }
                if (info.data.msg) {
                    this.$message.error(info.data.msg)
                }
            }).catch(err => {
                this.$message.error("文件上传失败!")
            })
            //上传完毕之后刷新文件列表
            this.selectFileList()

        },
        /**
         * 获取文件的MD5值
         * @param  file 
         */
        getFileMD5(file) {
            return new Promise((resolve, reject) => {
                let spark = new SparkMD5.ArrayBuffer();
                let fileReader = new FileReader();
                fileReader.readAsArrayBuffer(file.raw)
                fileReader.onload = function (e) {
                    spark.append(e.target.result);
                    let md5 = spark.end();
                    resolve(md5);
                };
            })
        },
        //上传组件监控
        uploadChange(file, fileList) {
            this.fileList = fileList
            this.percentShow = true
        },
        delFile() {
            this.fileList = [];
            this.progressPercent = 0;
            this.percentShow = false
        },
        handleRemove(file, fileList) {
            this.fileList = fileList
            if (fileList.length === 0) {
                this.percentShow = false
            }
        },
        handlePreview(file) {
            console.log(file);
        },
        //下载
        download() {
            this.multipleSelection.forEach(item => {
                let params = {
                    'id': item.id
                }
                console.log(item)
                allfileAPI.downloadFileApi(params).then(res => {
                    console.log(res.data)
                    const url = window.URL.createObjectURL(new Blob([res.data]))
                    const link = document.createElement('a');
                    link.href = url;
                    link.setAttribute('download', item.displayName);
                    document.body.appendChild(link);
                    link.click();

                })
            })
        },
        //右键菜单
        rowContextmenu(row, column, event) {
            console.log(row, " ", column, " ", event)
            this.fileOne = row//单个文件
            let fileS = [];
            fileS.push(row)//下载需要传递数组
            this.multipleSelection = fileS

            this.menuVisible = false
            this.menuVisible = true
            // 阻止右键默认行为
            event.preventDefault()
            this.$nextTick(() => {
                console.log(this.$refs['contextbutton'])
                this.$refs['contextbutton'].init(row, column, event)
            })
        },
        foo() { // 取消鼠标监听事件 菜单栏
            this.menuVisible = false
            document.removeEventListener('click', this.foo)
        },
        //单个文件夹打开
        handleZero() {
            console.log('点击菜单0')
            this.clickFileTable(this.fileOne)
        },
        //单个下载
        handleOne() {
            console.log('点击菜单一')
            this.download()
        },
        //单个文件或文件夹重命名
        handleTwo() {
            this.renameInput = this.fileOne.displayName
            this.renameVisible = true
        },
        handleThree() {
            console.log('点击菜单三')
        },
        //提交新重命名
        async upRename() {
            this.renameVisible = false
            if (this.fileOne.displayName === this.renameInput) {
                this.$message.error("重命名失败,未修改新名称!")
                return
            }
            this.fileOne.displayName = this.renameInput
            await allfileAPI.renameApi(this.fileOne).then(res => {
                console.log(res, "lllll")
            })
            //重新加载一下文件列表
            this.selectFileList()
        },
        //删除文件
        deleteFile(row) {
            console.log(row)
            allfileAPI.deleteFileApi(row).then(res => {
                if (res.data.code) {
                    this.$message.success("删除文件成功!")
                }
            })
            this.selectFileList();
        },
        //分享指定文件
        shareFile(row) {
            ShareFileAPI.shareOneFile(row).then(res => {
                this.$message.success(res.data.data)
            })
        },
        //上传校验
        uploadCheck(){
            allfileAPI.getTrans().then(res=>{
                if(res.data.data =="NO"){
                    this.$message.error("该用户传输权限被禁止！请联系管理员！")
                }else{
                    this.uploadVisible = true
                }
            })
            
        }





    },
    created() {
        //自动加载indexs方法
        this.selectFileList();
    },



}
export default options
</script>

<style lang="less" scoped>
/deep/ .el-breadcrumb__inner {
    color: #06a7ff;
}

.upload {
    margin-left: 10px;
}

.u-btn {
    display: none;
    font-size: 20px;
}

.el-table__body tr:hover {
    .u-btn {
        display: inline;
        margin-left: 20px;
        color: #06a7ff;

        .el-icon-view {
            font-size: large;
        }

        .el-icon-edit {
            font-size: large;
        }
    }
}
</style>